package com.social.security;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.social.utils.AESUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

import static com.social.constant.RedisConstants.AES_KEY_KEY;

/**
 * @BelongsProject: social
 * @BelongsPackage: com.social.security
 * @Author: zhm
 * @CreateTime: 2023-01-09  15:15
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private MyUserDetailsServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public MyAuthenticationProvider(MyUserDetailsServiceImpl userDetailsService) {
        setUserDetailsService(userDetailsService);
    }

    @SneakyThrows
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        String key = stringRedisTemplate.opsForValue().get(AES_KEY_KEY);
        System.out.println("123");
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            log.info("加密前密码"+presentedPassword );
            presentedPassword = AESUtil.decrypt(presentedPassword, key);
            log.info("解密后密码"+presentedPassword );
            if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
                this.logger.debug("Authentication failed: password does not match stored value");
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }
    }
}

